<template>
  <el-card class="box-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>配置TSMC格式</span>
      </div>
    </template>

    <el-form :inline="true" @submit.prevent>
      <el-form-item label="客户代码">
        <el-input
          v-model="searchForm.mtdCust"
          placeholder="请输入客户代码"
          clearable
        />
      </el-form-item>
      <el-form-item label="产品型号">
        <el-input
          v-model="searchForm.mtdDevice"
          placeholder="请输入产品型号"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="onSearch"
          >搜索</el-button
        >
        <el-button @click="onReset">重置</el-button>
        <el-button type="success" @click="handleCreate">新建配置</el-button>
      </el-form-item>
    </el-form>

    <el-divider />

    <el-table
      :data="pagedTableData"
      border
      stripe
      :style="{ width: '100%' }"
      v-loading="loading"
    >
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="mtdCust" label="客户代码" />
      <el-table-column prop="mtdDevice" label="产品型号" />
      <el-table-column prop="mtdRemark" label="备注" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            size="small"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredTableData.length"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑配置' : '新建配置'"
      width="500px"
      :before-close="handleClose"
    >
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
        <el-form-item label="客户代码" prop="mtdCust">
          <el-input v-model="form.mtdCust" placeholder="请输入客户代码" />
        </el-form-item>
        <el-form-item label="产品型号" prop="mtdDevice">
          <el-input v-model="form.mtdDevice" placeholder="请输入产品型号" />
        </el-form-item>
        <el-form-item label="备注" prop="mtdRemark">
          <el-input
            v-model="form.mtdRemark"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import axios from "axios";

defineOptions({
  name: "TsmcGeneraterConfig"
});

interface TableItem {
  id?: string;
  mtdCust: string;
  mtdDevice: string;
  mtdRemark: string | null;
}

// const API_BASE_URL = "https://localhost:44389"; //调试用地址
const API_BASE_URL = "http://10.0.8.42:8089"; // 发布用地址

const API_CONFIG_QUERY = `${API_BASE_URL}/TsmcConfig/query`;
const API_CONFIG_CREATE = `${API_BASE_URL}/TsmcConfig/create`;
const API_CONFIG_UPDATE = `${API_BASE_URL}/TsmcConfig/update`;
const API_CONFIG_DELETE = `${API_BASE_URL}/TsmcConfig/delete`;

const loading = ref(false);
const allRecords = ref<TableItem[]>([]);

const tableData = ref<TableItem[]>([]);

const searchForm = reactive({
  mtdCust: "",
  mtdDevice: ""
});

const filteredTableData = computed(() => {
  return allRecords.value.filter(item => {
    const customerMatch = item.mtdCust.includes(searchForm.mtdCust);
    const productMatch = item.mtdDevice.includes(searchForm.mtdDevice);
    return customerMatch && productMatch;
  });
});

const currentPage = ref(1);
const pageSize = ref(10);

const pagedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredTableData.value.slice(start, end);
});

const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const form = reactive<TableItem>({
  id: undefined,
  mtdCust: "",
  mtdDevice: "",
  mtdRemark: null
});

const rules = reactive<FormRules<TableItem>>({
  mtdCust: [{ required: true, message: "请输入客户代码", trigger: "blur" }],
  mtdDevice: [{ required: true, message: "请输入产品型号", trigger: "blur" }]
});

const fetchConfigList = async () => {
  loading.value = true;
  const loadingInstance = ElLoading.service({
    lock: true,
    text: "加载中...",
    background: "rgba(0,0,0,0.3)"
  });

  try {
    const response = await axios.get(API_CONFIG_QUERY, {
      params: {
        page: 1,
        pageSize: 99999
      }
    });
    if (Array.isArray(response.data)) {
      allRecords.value = response.data.map(item => ({
        ...item,
        id: item.id || Math.random().toString(36).substring(2, 11)
      })) as TableItem[];
    } else {
      ElMessage.error("获取数据失败：后端返回数据格式不正确");
      allRecords.value = [];
    }
  } catch (error) {
    console.error("获取配置列表失败:", error);
    ElMessage.error("获取配置列表失败");
    allRecords.value = [];
  } finally {
    loading.value = false;
    loadingInstance.close();
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

const onSearch = () => {
  currentPage.value = 1;
  ElMessage.success("搜索成功");
};

const onReset = () => {
  searchForm.mtdCust = "";
  searchForm.mtdDevice = "";
  currentPage.value = 1;
  ElMessage.info("已重置");
};

const handleCreate = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

const handleEdit = (row: TableItem) => {
  isEdit.value = true;
  Object.assign(form, row);
  dialogVisible.value = true;
};

const handleDelete = (id: string) => {
  ElMessageBox.confirm(`确定删除该配置吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: "删除中...",
        background: "rgba(0,0,0,0.3)"
      });
      try {
        const response = await axios.delete(`${API_CONFIG_DELETE}/${id}`);
        if (response.status === 204) {
          ElMessage.success("删除成功");
          fetchConfigList();
        } else {
          ElMessage.error(response.data?.message || "删除失败");
        }
      } catch (error) {
        console.error("删除配置失败:", error);
        ElMessage.error("删除配置失败");
      } finally {
        loadingInstance.close();
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async valid => {
    if (valid) {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: isEdit.value ? "更新中..." : "创建中...",
        background: "rgba(0,0,0,0.3)"
      });
      try {
        let response;
        const submitForm: TableItem = {
          mtdCust: form.mtdCust,
          mtdDevice: form.mtdDevice,
          mtdRemark: form.mtdRemark,
          id: isEdit.value ? form.id : ""
        };
        if (isEdit.value) {
          response = await axios.put(
            `${API_CONFIG_UPDATE}/${form.id}`,
            submitForm
          );
        } else {
          const createForm = {
            mtdCust: form.mtdCust,
            mtdDevice: form.mtdDevice,
            mtdRemark: form.mtdRemark
          };
          response = await axios.post(API_CONFIG_CREATE, createForm);
        }

        if (isEdit.value ? response.status === 204 : response.status === 201) {
          ElMessage.success(isEdit.value ? "更新成功" : "创建成功");
          dialogVisible.value = false;
          fetchConfigList();
        } else {
          ElMessage.error(
            response.data?.message || (isEdit.value ? "更新失败" : "创建失败")
          );
        }
      } catch (error) {
        console.error(isEdit.value ? "更新配置失败:" : "创建配置失败:", error);
        ElMessage.error(isEdit.value ? "更新配置失败" : "创建配置失败");
      } finally {
        loadingInstance.close();
      }
    }
  });
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const resetForm = () => {
  formRef.value?.resetFields();
  Object.assign(form, {
    id: undefined,
    mtdCust: "",
    mtdDevice: "",
    mtdRemark: null
  });
};

onMounted(() => {
  fetchConfigList();
});
</script>

<style scoped>
.box-card {
  margin: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
